package com.yuanye.gwcit.fragments;

import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.yuanye.gwcit.GW;
import com.yuanye.gwcit.utils.NTPClient;
import com.yuanye.yeecho.base.CommonTaskFragment;
import com.yuanye.yeecho.utils.YY;

public class RtcSyncFragment extends CommonTaskFragment {

    public RtcSyncFragment() {
        setTaskName("时钟同步");
    }

    @Override
    public void execTask() {
        super.execTask();
        String rtcIp = GW.cfgPcba.getRtcSyncIp();
        if (rtcIp.contains("192.168.")){
            checkRtcTime(rtcIp);
        }else{
            appendLog("ip号段不对，跳过rtc同步检查");
            appendLog("时钟同步通过");
            passAndNext();
        }
    }

    Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            int code = msg.what;
            String info = msg.obj.toString();
            if (code == 200){
                appendLog(info);
                passAndNext();
            }else{
                appendLogF(info);
                setFail();
            }
        }
    };

    private String formatTime(long time){
        return YY.formatTime(time, "yyyy-MM-dd HH:mm:ss:SSS");
    }

    private void checkRtcTime(String rtcIp){
        new Thread(new Runnable() {
            @Override
            public void run() {
                long ntpTime = getTimeFromNtpServer(rtcIp);
                //增加8个时区
//                ntpTime = ntpTime + 8 * 3600 * 1000;
                appendLog("NTP时间："+formatTime(ntpTime));
                long currentTime = System.currentTimeMillis();
                appendLog("当前时间："+formatTime(currentTime));
                Message msg = Message.obtain();
                long deltaTime = Math.abs(ntpTime - currentTime);
                appendLog("误差："+deltaTime+"ms");
                int delta = 1000;
                try {
                    delta = Integer.parseInt(GW.cfgPcba.getRamModel());//借用ramModel值用作误差标准
                }catch (NumberFormatException e){
                    appendLog("RAM_MODEL值转换成int型出错");
                }
                if (deltaTime < delta){//误差判断
                    msg.what = 200;
                    msg.obj = "符合标准："+delta+"ms，校验成功";
                }else{
                    msg.what = -1;
                    msg.obj = "不符合标准："+delta+"ms，校验失败";
                }
                handler.sendMessage(msg);
            }
        }).start();
    }

    private long getTimeFromNtpServer(String ntpHost) {
        appendLog("get time from apache net :" + ntpHost);
        NTPClient ntpClient = new NTPClient();
        ntpClient.initNTPClient(ntpHost, 5000);
        long time = ntpClient.getNTPServerLongTime();
        ntpClient.stopNTPClient();
        return time;
    }
}
